package com.hewanglan.oss.controller;

import com.alibaba.fastjson.JSON;
import com.hewanglan.oss.entity.FileInfo;
import com.hewanglan.oss.entity.Result;
import com.hewanglan.oss.service.FileService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/oss")
public class FileController {
    @Resource
    private FileService fileService;

//    @NacosValue(value="${storage.service.type}",autoRefreshed = true)
//    private String storageType;

    /**
     * 获取所有桶
     * @return
     * @throws Exception
     */
    @GetMapping("/getAllBuckets")
    public String testGetAllBuckets()throws Exception{
        List<String> allBucket = fileService.getAllBucket();
        String jsonString = JSON.toJSONString(allBucket);
        return jsonString;
    }
    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile uploadFile, String bucket, String objectName) throws Exception {
        String url = fileService.uploadFile(uploadFile, bucket, objectName);
        return Result.ok(url);
    }
    /**
     * 列出桶下所有文件
     * @param bucket
     * @return
     */
    @GetMapping("/listFiles")
    public Result<List<FileInfo>> listFiles(String bucket) throws Exception{
        List<FileInfo> allFile = fileService.getAllFile(bucket);
        return Result.ok(allFile);
    }

    /**
     * 下载文件
     * @param bucket
     * @param objectName
     * @return
     * @throws Exception
     */
    @GetMapping("/downloadFile")
    public InputStream downloadFile(String bucket,String objectName)throws Exception{
        InputStream download = fileService.download(bucket, objectName);
        return download;
    }

    /**
     * 删除文件
     * @param bucket
     * @param objectName
     * @return
     * @throws Exception
     */
    @GetMapping("/deleteFile")
    public Result deleteFile(String bucket,String objectName)throws Exception{
        fileService.deleteObject(bucket,objectName);
        return Result.ok("删除文件成功！");
    }

    /**
     * 删除桶
     * @param bucket
     * @return
     * @throws Exception
     */
    @GetMapping("/deleteBucket")
    public Result deleteBucket(String bucket) throws Exception{
        fileService.deleteBucket(bucket);
        return Result.ok("成功删除桶！");
    }

    /**
     * 获取文件URL
     * @param bucket
     * @param objectName
     * @return
     * @throws Exception
     */
    @RequestMapping("/getUrl")
    public String getUrl(String bucket, String objectName) throws Exception {
        return fileService.getUrl(bucket, objectName);
    }

}
